import dash
import dash_bootstrap_components as dbc
import numpy as np
from dash import dcc, html, Input, Output
import plotly.express as px
import pandas as pd
import ExcelRead
from country import get_cn_name

################################# 初始化数据 ######################################
# 创建示例数据
df = pd.DataFrame({
    'Year': [2014, 2015, 2016, 2017, 2018, 2019, 2020],
    'GDP': [1.8, 2.0, 2.2, 2.5, 2.7, 3.0, 3.2],
    'Population': [100, 102, 104, 106, 108, 110, 112]
})

# 取出城镇化数据
urban_df = ExcelRead.read_excel_to_df(
    "./assets/API_SP.URB.TOTL.IN.ZS_DS2_en_excel_v2_29.xls")
# 取出供水数据
supply_dict = ExcelRead.read_csv_to_df(
    "./assets/share-of-the-population-using-safely-managed-drinking-water-sources.csv")

# 取出城镇化国家，index就是表格最左面的索引
urban_country = urban_df.index.to_list()
# 取出供水国家
supply_dict.keys()
supply_valid_keys = [key for key, country_data in supply_dict.items() if not pd.isna(country_data[1][0])]

# 找出城镇化数据和供水数据的交集
intersection = set(urban_country) & set(supply_valid_keys)

# 集合做差
# diff_supply = set(supply_valid_keys) - intersection
# diff_urban = set(urban_country) - intersection
intersection_list = sorted(list(intersection))
# print("交集的长度:", len(intersection_list))
# print("交集的元素:", intersection_list)

# 根据两个国家的交集，建立选择框
# 如果get_cn_name没找到，则使用item
country_options = [{'label': get_cn_name(item) if get_cn_name(item) else item, 'value': item}
                   for item in intersection_list
                   ]


# 用于初始化fig
def empty_fig():
    empty_df = pd.DataFrame()
    emp_fig = px.scatter(empty_df)
    return emp_fig


# 初始化全局变量
fig = empty_fig()


def update_fig(country_name):
    global fig

    # 获取国家对应的城镇化数据
    urban_data = urban_df.loc[country_name]
    # 配置urban_data的标题
    # columns_as_lists = {col: urban_data[col].tolist() for col in urban_data.columns}
    # list1 = urban_data.index.to_list()
    # list2 = urban_data.values.tolist()
    urban_temp = {'年份': urban_data.index.to_list(),
                  '数据类型': ['城镇人口占比'] * len(urban_data.index.to_list()),
                  '百分比': urban_data.values.tolist()}
    urban_df_temp = pd.DataFrame(urban_temp)
    fig = px.scatter(urban_df_temp,
                     x='年份',
                     y='百分比',
                     color='数据类型',
                     title=f'{get_cn_name(country_name)}   城镇人口占比与城镇供水率比较',
                     color_discrete_sequence=['red'])

    # 获取国家对应的供水率
    supply_data = supply_dict.get(country_name)
    supply_temp = {'年份': supply_data[0],
                   '数据类型': ['城镇供水率'] * len(supply_data[0]),
                   '百分比': supply_data[1]}
    supply_df = pd.DataFrame(supply_temp)
    # 通过color区分'城镇化占比'和'城镇供水率'
    fig.add_trace(px.scatter(supply_df,
                             x='年份',
                             y='百分比',
                             color='数据类型',
                             title=f'{get_cn_name(country_name)}   城镇人口占比与城镇供水率比较',
                             color_discrete_sequence=['blue']).data[0])

    fig.update_layout(
        title_x=0.5  # 0.5 表示标题居中
    )


# 设置默认选中项
update_fig("Algeria")
default_value = 'Algeria'  # 设置 Banana 为默认选中的项

# 初始化Dash应用
# app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
app = dash.Dash(__name__)
# 应用布局
app.layout = html.Div(
    dbc.Container(
        [
            html.Br(),
            html.Br(),
            html.H2("城镇人口占比 与 城镇供水率 比较", style={'textAlign': 'center'}),
            # html.Div(style={'height': '20px'}),
            html.Br(),
            html.Br(),
            dbc.Row(
                dbc.Col(
                    dcc.Dropdown(
                        id='country-select',
                        options=country_options,
                        value=default_value,
                        # style={'width': '80%'},
                        # multi=True
                    )
                )
            ),
            dbc.Row(
                dbc.Col(
                    dcc.Graph(
                        id='urban-supply-scatter',
                        figure=fig,
                        style={'width': '100%'},
                        # config={'displayModeBar': False}
                    ),
                    # width=12
                )
            )
        ],
        fluid=True
    )
)

# prevent_initial_call=True 第一次初始化会被阻止
@app.callback(Output('urban-supply-scatter', 'figure'),
              Input('country-select', 'value'),
              prevent_initial_call=True)
def country2chart(country):
    global fig
    print('country2chart run ...')
    country_data = supply_dict.get(country)

    if (country_data is not None) and (not np.isnan(country_data[1][0])):
        try:
            update_fig(country)
        except Exception as err:
            print(err)
    else:
        # 因为已设置默认值，所以初始化后不会为空，如果确实出现了空值国家，就将fig置空
        fig = empty_fig()
    return fig


server = app.server
# 运行应用
if __name__ == '__main__':
    app.run_server(debug=True)
